<script setup lang="ts">
import selectDialog from './select/index.vue';
import { tableConfig } from './config/table-config';
import { formConfig } from './config/form-config';
import { formatInput, transformDataToKeys } from '@/utils';
import useEmit from '@/hooks/useEmitter';
import usePageSave from '@/hooks/usePageSave';
import { doAddSupplier } from '@/api/base/supplier/index';
import { message } from '@/components/q-message/message';
import { Plus } from '@element-plus/icons-vue';
import addDataStore from '@/store/modules/addDataStore';
import type { MaterialRecords, SupplierRecords } from '@/api/base/supplier/model/type';
import type { SupplerUpdateForm } from '@/views/Base/Supplier/type';

defineOptions({
    name: 'SupplierAdd'
});

const store = addDataStore();

const STORE_KEY = 'supplerAddData';
/**
 * @: 离开页面时不进行定位 进行计算时会有bug
 */
const { startRecording, isUpdate } = useEmit(STORE_KEY, () => (sticky.value = false)); // 页面标签路由关闭二次确认事件监听 EventBus

const selectRef = ref<InstanceType<typeof selectDialog>>();

const initSupplerUpdateForm = () => {
    return {
        supplierCode: null,
        supplierName: null,
        supplierPerson: null,
        supplierPhone: null
    };
};

const supplerUpdateForm = ref<SupplerUpdateForm>(initSupplerUpdateForm());

const excludeKey = ref(['tableData']);
const { modalSlotRef, loading } = useModal({
    appendData: supplerUpdateForm,
    excludeKey
});

/**
 * 校验相关
 */
const { popoverVisible, popoverErrMsg, handleInput, handleFocus, handleValidFieldPass } = useValid({
    position: 'left',
    formConfig: formConfig.items,
    formFields: supplerUpdateForm,
    mountErrId: formConfig.id
});

/**
 * @: 获取数据
 */
const handleGetData = () => {
    return new Promise(resolve => {
        const res = { data: { records: materialList.value } };
        resolve(res);
    });
};

/**
 * @: 选择物料
 */
const openMaterial = () => {
    selectRef.value?.open(materialList.value);
};

/**
 * @: 删除单条供应产品
 */
const handleDel = (row?: SupplierRecords, index?: number) => {
    materialList.value = materialList.value.filter(
        (item, idx) => item.materialId !== row?.materialId || idx !== index
    );
    modalSlotRef.value?.getData?.();
};

/**
 * @: 选中数据
 */
const materialList = ref<Partial<MaterialRecords>[]>([]);
const selectMaterial = (list: MaterialRecords[]) => {
    materialList.value = [...materialList.value, ...list];
    modalSlotRef.value?.getData?.();
};

/**
 * @: 点击确定按钮
 */
const submit = async () => {
    const formValid = handleValidFieldPass();
    const tableValid = modalSlotRef.value?.handleValidFieldPass();
    if (formValid && tableValid) {
        const dataList = materialList.value.map(item => {
            // 通过所传入的 key 获取对应参数

            return transformDataToKeys(item, [
                'supplierId',
                'materialId',
                'materialName',
                'materialCode',
                'finishedProductRate',
                'quasiDeliveryRate'
            ]);
        });
        const supplierData = {
            ...supplerUpdateForm.value,
            supplierMaterials: dataList
        };
        try {
            const res = await doAddSupplier(supplierData);
            if (res) {
                message.success(`新增供应商成功！`);
                usePageSave('/Supplier');
                return res;
            }
        } catch (error) {
            console.log('error', error);
        }
    }
};

/**
 * @: 初始化时不进行定位 进行计算时会有bug
 */
onActivated(() => {
    handleSticky();
    isUpdate(setData);
});

const sticky = ref(false); // 定位
const handleSticky = () => {
    setTimeout(() => {
        sticky.value = true;
    }, 800);
};
/**
 * @: 初始化
 */
const route = useRoute();
const setData = () => {
    materialList.value = [];
    supplerUpdateForm.value = initSupplerUpdateForm();
    modalSlotRef.value?.getData?.();
    startRecording(route.name as string, {
        materialList,
        supplerUpdateForm
    });
};

onDeactivated(() => {
    sticky.value = false;
});

onUnmounted(() => {
    store.handleAddData(STORE_KEY);
});
</script>

<template>
    <q-page>
        <div :class="{ sticky }" class="top-line">
            <!-- 基础信息 -->

            <q-form-item :id="formConfig.id!" class="f-1">
                <h2 class="m-title--common m-b-8">基础信息</h2>
            </q-form-item>
            <!-- 确定按钮 -->
            <q-submit-button
                size="default"
                :hide-label="true"
                align="right"
                :horizontal="true"
                :loading="loading"
                :cancel-button="false"
                @save="submit"
            />
        </div>

        <el-row :gutter="32" class="p-l-8 p-r-8">
            <el-col
                v-for="item in formConfig.items"
                :key="item.validProps?.id"
                :span="6"
                class="role-main__header form-common m-b-18"
            >
                <label class="is-column"
                    ><span>{{ item.validProps?.required ? '*' : '&nbsp;' }}</span
                    >{{ item.columnProps?.label }}:</label
                >
                <q-form-item :id="item.validProps?.id!" class="role-main-form__item">
                    <el-input
                        v-model.trim="supplerUpdateForm[item.modelKey!]"
                        v-bind="item.elInputProps"
                        :placeholder="`请输入${item.columnProps?.label}`"
                        @focus="
                            (e: any) =>
                                handleFocus(e, supplerUpdateForm, {
                                    config: item
                                })
                        "
                        @input="
                            supplerUpdateForm[item.modelKey!] = formatInput(
                                supplerUpdateForm,
                                item.modelKey!,
                                item.validFormatType
                            )
                        "
                        @keyup="
                            (e: any) =>
                                handleInput(e, supplerUpdateForm, {
                                    config: item
                                })
                        "
                        @blur="popoverVisible = false"
                    />
                </q-form-item>
            </el-col>
        </el-row>

        <base-table
            ref="modalSlotRef"
            class="m-t-8"
            :show-setting="false"
            :show-page="false"
            :table-config="tableConfig"
            :get-data-fn="handleGetData"
            :close-edit="true"
            action-width="80px"
            @del="handleDel"
        >
            <template #tableHeadStart>
                <!-- 供应物料 -->
                <h2 class="m-title--common">供应物料</h2>
            </template>
            <template #tableHeadEnd>
                <el-button type="primary" :icon="Plus" @click="openMaterial"> 选择物料 </el-button>
            </template>

            <!-- 成品率 -->
            <template #finishedProductRate="{ row, item }">
                <q-form-item :id="item.validProps!.id!">
                    <el-input-number
                        v-model="row.finishedProductRate"
                        style="width: 80%"
                        :controls="false"
                        :precision="2"
                        :max="100"
                        :min="1"
                        @focus="
                            (e: any) =>
                                handleFocus(e, row, {
                                    config: item
                                })
                        "
                        @blur="popoverVisible = false"
                        @keyup="
                            (e: any) =>
                                handleInput(e, row, {
                                    config: item
                                })
                        "
                    >
                    </el-input-number>
                    %
                </q-form-item>
            </template>

            <!-- 准交率 -->
            <template #quasiDeliveryRate="{ row, item }">
                <q-form-item :id="item.validProps!.id!">
                    <el-input-number
                        v-model="row.quasiDeliveryRate"
                        style="width: 80%"
                        :controls="false"
                        :precision="2"
                        :min="1"
                        :max="100"
                        @focus="
                            (e: any) =>
                                handleFocus(e, row, {
                                    config: item
                                })
                        "
                        @blur="popoverVisible = false"
                        @keyup="
                            (e: any) =>
                                handleInput(e, row, {
                                    config: item
                                })
                        "
                    >
                    </el-input-number>
                    %
                </q-form-item>
            </template>
        </base-table>

        <!-- 校验提示框 -->
        <q-valid-popover
            :popover-visible="popoverVisible"
            :popover-err-msg="popoverErrMsg"
            position="left"
        />

        <!-- 选择物料弹框 -->
        <select-dialog ref="selectRef" @submit="selectMaterial" />
    </q-page>
</template>

<style scoped lang="scss">
@include b(role-main-form) {
    @include e(item) {
        width: 100%;
        max-width: 1000px;
    }
}

@include b(role-main__header) {
    color: var(--el-color-danger);
}

@include b(main) {
    width: 90%;
    margin: 0 auto;
}

@include b(include) {
    flex: 1;
}

@include b(title) {
    font-weight: 700;
}

@include b(top-line) {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    padding: 0 16px;
    margin: -8px -16px 0;
}

@include b(sticky) {
    position: sticky;
    top: 48px;
    z-index: 15;
}

:deep() {
    .action > span {
        margin-left: 0 !important;
    }
}
</style>
